package com.rslai.base.tool.servertest.command;

import com.rslai.base.tool.servertest.context.Context;
import com.rslai.base.tool.servertest.model.KeyValueStore;
import com.rslai.base.tool.servertest.response.Response;
import com.rslai.base.tool.servertest.util.CloneUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;

public class SetStepCommand extends ParameterizedCommand {
    public SetStepCommand(List<KeyValueStore> params) {
        super(params);
    }

    protected Response doExecuteInternal(Response preResult, List<KeyValueStore> processedParams, Context context) {
        this.logger.info("set command<{}> is staring ...", getParamsAsString(processedParams));
        context.addContext(convertToMap(processedParams));
        return preResult;
    }

    public StepCommand doClone() {
        return new SetStepCommand(CloneUtil.cloneKeyValueStore(this.params));
    }

    public Map<String, Object> toReport() {
        Map details = new HashMap();
        details.put("stepName", "设置Case环境变量:");
        details.put("params", this.params);
        return details;
    }

    private Map<String, Object> convertToMap(List<KeyValueStore> processedParams) {
        Map result = new HashMap();
        for (KeyValueStore kvs : processedParams) {
            result.put(kvs.getName(), kvs.getValue());
        }
        return result;
    }

    private String getParamsAsString(List<KeyValueStore> params) {
        if (params == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (KeyValueStore kv : params) {
            sb.append(kv.getName()).append("=").append(kv.getValue()).append("&");
        }

        return sb.toString();
    }
}
